$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';
$(document).ready(function () {
	if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0"){
		var $moudle = $('#data-moudle');
		var module = $moudle.val();
		var $id = $('#data-id');
		var id = $id.val();
	}else {
		var $body = $('body');
		var module = $body.data('moudle');
		var id = $body.data('id');
	}
	//全局缓存
	var supplierList = {}; //邀请供应商
    var supplierListArray = new Array();//邀请供应商
	var projectUserList =  {};//角色
	var attachmentList = {}; //附件
    var addressData=getAddressData();//获取需要回显得地址数据
    //显示省市区
    showProvince('level','1',null,addressData);//页面初始化(编辑页回显，新增页初始化)
    //选择省市chang事件
    $('#deliveryProvince').bind('change', selProvince);
    $('#deliveryCity').bind('change', selCity);

	var $assureMoney = $('input[name="rulesBo.needAssureMoney"]');
	var $roleTable = $('#roleTable');
	//定向非定向选择处理
	(function () {
		var checkes = $('input.js-check');
		var $public = $('.fb-zz input');
		$('#checkedDiv').on('change',':radio', function () {
			var needCheck = (this.value == 1);
			checkes.prop('checked',needCheck);
			checkes.attr('disabled',needCheck);
			//定向情况下 公开的相关内容屏蔽，防止提价到后台
			//console.log($public.find(':checkbox'));
			$public.prop('checked',false);
			$public.attr('disabled',!needCheck);
		});

		//财务审核控制
		$assureMoney.on('change', function () {
			var money = this.value;
			var $moneyChecks = $roleTable.find('.js-money');
			if(money == 0){
				$moneyChecks.prop('checked',false);
			}
			$moneyChecks.attr('disabled',money == 0);
		});
		$assureMoney.filter(':checked').trigger('change');
	})();

	//从历史询单创建
	(function(){
		//初始化jqGrid 默认不加载数据
		var jqGrid = null;

		function initJqGrid(){
			return RFQ.jqGrid('#jqGridHis').init({
				url: ctx+'/rfqRequest/rfqRequestList',
				autoLoad:false,
				singleSelect: true,
				colModel: [
					{
						label: '主键',
						name: 'id',
						index: 'id',
						width: 20,
						key: true,
						hidden: true
					},
					{
						label: '询价单号',
						name: 'unifiedRfqNum',
						index: 'UNIFIED_RFQ_NUM',
						hidden:true,
						width: 20,
						formatter:selectFormatter
					},
                    {
                        label: '询价单号',
                        name: 'ouRfqNum',
                        index: 'OU_RFQ_NUM',
                        width: 20,
                        formatter:selectFormatter
                    },
					{
						label: '询单标题',
						name: 'title',
						index: 'TITLE',
						width: 20,
					},
					{
						label: '创建人',
						name: 'recCreatorUsername',
						index: 'REC_CREATOR_USERNAME',
						width: 20
					},
					{
						label: '创建时间',
						name: 'recCreateTime',
						index: 'REC_CREATE_TIME',
						width: 20
					},
					{
						label: '询单状态',
						name: 'type',
						index: 'TYPE',
						width: 20,
						formatter:formatRfqRequestType
					}
				],
				postData:{rfqMethod:"RAQ"},
				sortname: 'REC_CREATE_TIME',
				sortorder: 'desc',
				pager: "#jqGridHisPager",
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
		}

		$("#btnSearchHis").click(function () {
			var startTime = $('#recCreateTime').val();
			var endTime = $('#recCreateTimeEnd').val();
			//console.log('startTime:'+startTime+',endTime:'+endTime);
			if(endTime != "" && startTime>endTime){
				RFQ.warn('创建日期输入异常!');
			}
			jqGrid.reload(form2Json("searchFormHis"));
		});
		//弹窗显示加载数据
		$('#myModa1').on('shown.zui.modal', function() {
			$('#searchFormHis input[type="text"]').not('.phcolor').val('');
			$.placeholder();
			jqGrid = initJqGrid();
			jqGrid.reload(form2Json("searchFormHis"));
			/*if(!jqGrid){
				jqGrid = initJqGrid();
				jqGrid.reload();
			}*/
			jqGrid.resize();
		});

		/**
		 * 询单编号链接跳转
		 */
		function selectFormatter(cellvalue, options, rawObject) {
			var id = rawObject.id;
			return "<a class='blue' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' target='_blank'>"+cellvalue+"</a>";
		}

		window.addHis = function(){
			var ids = $('#jqGridHis').jqGrid('getGridParam', 'selrow');
			//console.log('ids:'+ids);
			if(!ids || (ids != undefined && !ids.length)){
				$('#myModa1').modal('hide');
				return;
			}/* else if(ids.length > 1) {
				$.zui.messager.show('选择的数据超出范围！', {placement: 'center', type: 'warning', icon: 'icon-warning-sign'});
				return;
			} */else {
				$("#rid").val(ids);
				//console.log('rid:'+$("#rid").val());
				var $confirmBtn = $('#myModa1').find('.modal-footer .btn-primary');
				$confirmBtn.attr('disabled',true);
				$.ajax({
					type: "POST",
					url: ctx+"/rfqRequest/addRequestByHis",
					data: {
						rid: $("#rid").val()
					},
					success: function (data) {
						$confirmBtn.attr('disabled',false);
						if (data.status == 'success') {
							$('#myModa1').modal('hide');
							//成功后跳转到编辑页
							location.href = ctx+"/rfqRequest/toUpdateRfqRequest?id="+data.requestId;
						} else {
							RFQ.error('sorry,出错了！');
						}
					}
				});
			}
		}
	})();
	//END

	//邀请供应商
	(function(){

		var jqGrid = null;
		var sdata = [];
        var rowIndex = 0;
        var $supplistModal = $('#supplistModal');
		var $form = $supplistModal.find('form');
		$supplistModal.on('shown.zui.modal',function(){
			getAttData("#jqGridsup","#jqGridPagersup");

		});
		if(module =='edit'){

        var isSupplierRequirement = $("#isSupplierRequirement").val();
        }else{
            if($(":checkbox[name=isSupplierRequirement]").prop("checked")){
                var isSupplierRequirement = $(":checkbox[name=isSupplierRequirement]").val();
            }else{
                var isSupplierRequirement = '0';
            }

        }
        if (isSupplierRequirement == '0') {
            $("#supplierListJqGrid").jqGrid({
                datatype: 'local',
                rownumbers: true,
                rownumWidth: 50,
                colModel: [
                    {
                        label: 'id',
                        name: 'id',
                        index: 'id',
                        key: true,
                        hidden: true
                    },
                    {
                        label: '供应商U代码',
                        name: 'supplierCode',
                        index: 'supplierCode',
                        align: 'center'
                    },
                    {
                        label: '特邀供应商名称',
                        name: 'supplierName',
                        index: 'supplierName',
                        align: 'center'
                    },
                    {
                        label: '联系人',
                        name: 'linkmanName',
                        index: 'linkmanName',
                        align: 'center'
                    },
                    {
                        label: '联系电话',
                        name: 'linkmanTelphone',
                        index: 'linkmanTelphone',
                        align: 'center'
                    },
                    {
                        label: '微信状态',
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        align: 'center'
                    },
                    {
                        label: '操作',
                        name: 'bindWechat',
                        index: 'bindWechat',
                        align: 'center',
                        formatter: deleteFormatter
                    }
                ],
                viewrecords: true,
                //sortname: 'userLoginNo',
                //sortorder: 'asc',
                width: "970",
                height: "100%",
                pager: "#supplierListjqGridPager",
                rowNum: 20,//每页显示记录数
                rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
            });
			if(($("#dataSource").val() =='JFE' || $("#dataSource").val() =='NBBX')&& $("#publicBiddingFlag").val()=='0') {
				$("#supplierListJqGrid").setGridParam().hideCol("bindWechat").trigger("reloadGrid");
			}
		} else if (isSupplierRequirement == '1') {
            $("#supplierListJqGrid").jqGrid({
                datatype: 'local',
                rownumbers: true,
                rownumWidth: 50,
                colModel: [
                    {
                        label: 'id',
                        name: 'id',
                        index: 'id',
                        key: true,
                        hidden: true
                    },
                    {
                        label: '供应商U代码',
                        name: 'supplierCode',
                        index: 'supplierCode',
                        align: 'center'
                    },
                    {
                        label: '特邀供应商名称',
                        name: 'supplierName',
                        index: 'supplierName',
                        align: 'center'
                    },
                    {
                        label: '联系人',
                        name: 'answerUsername',
                        index: 'answerUsername',
                        align: 'center'
                    },
                    {
                        label: '联系电话',
                        name: 'linkmanTelphone',
                        index: 'linkmanTelphone',
                        align: 'center'
                    },
                    {
                        label: '微信状态',
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        align: 'center'
                    },
                    {
                        label: '操作',
                        name: 'companyId',
                        index: 'companyId',
                        align: 'center',
                        formatter: deleteFormatter
                    }
                ],
                viewrecords: true,
                //sortname: 'userLoginNo',
                //sortorder: 'asc',
                width: "100%",
                height: "100%",
                pager: "#supplierListjqGridPager",
                rowNum: 20,//每页显示记录数
                rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
            });
        }
        if (module == 'edit') {
            if (isSupplierRequirement == '0') {

                var supplierListJqGrid = JSON.parse($("#supplierList").val());
                //当前存在的数据加入缓存
				if(supplierListJqGrid != undefined && supplierListJqGrid != null   ){
                    $.each(supplierListJqGrid, function (i, supplier) {
                        supplierList[supplier.supplierCode] = supplier;
                    });
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListJqGrid}).trigger('reloadGrid');

				}else{
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: {}}).trigger('reloadGrid');
				}
            } else if (isSupplierRequirement == '1') {
                var preauditSupplierListJqGrid = JSON.parse($("#preauditSupplierList").val());
                if (preauditSupplierListJqGrid != undefined && preauditSupplierListJqGrid != null) {
                    $.each(preauditSupplierListJqGrid, function (i, preauditSupplier) {
                        supplierList[preauditSupplier.supplierCode] = preauditSupplier;
                    });
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: preauditSupplierListJqGrid}).trigger('reloadGrid');

                }else{
                    $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: {}}).trigger('reloadGrid');
				}

            }
        }
        $("#supplierListJqGrid").jqGrid('resizeGrid');
		function getAttData(grid,page){
			//启用内存分页
			jqGrid = RFQ.jqGrid(grid).init({
				datatype:"local",
				multiselect: true,
				colModel: [
					{
						name: 'companyId',
						index: 'companyId',
						key: true,
						hidden: true
					},
                    {
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        hidden: true
                    },
					{
						name: 'companyId',
						index: 'companyId',
						hidden: true
					},
					{
						label: '供应商U代码',
						name: 'supplierCode',
						width: 20,
					},
					{
						label: '供应商名称',
						name: 'supplierName',
						width: 20,
					},
					{
						label: '所属类别',
						name: 'type',
						width: 20,
					},
					{
						label: '供应商等级',
						name: 'deviceDealerGrade',
						width: 20,
					},
					{
						label: '联系人',
						name: 'linkmanName',
						width: 20,
					},
					{
						label: '联系电话',
						name: 'linkmanTelphone',
						width: 20
					}
				],
				pager: page,
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
			$.post(ctx+'/rfqSupplierListNew/rfqSupplierListListNew',{}, function (data) {
				sdata = (data.list||[]).filter(function (item) {
					return !supplierList[item.supplierCode];
				});
				// $form[0].reset();
				$('#supplistModal input[type="text"]').not('.phcolor').val('');
				$.placeholder();
				jqGrid.loadLocal(sdata);
				jqGrid.resize();
			},'json')
		}

		$("#btnSearch").click(function () {
			var validJson = {};
			$form.find(':text,select').each(function () {
				if($(this).hasClass("phcolor")){
					this.value && (validJson[this.name] = '');
				}else{
					this.value && (validJson[this.name] = this.value);
				}

			});
			var searchData = sdata.filter(function (item) {
				var isValid = true;
				for(var key in validJson){
					if(!isValid) return false;
					if(key == 'supplierName' || key == 'supplierCode' || key == 'type'){
						isValid =item[key] &&  ~item[key].indexOf(validJson[key]);//模糊匹配
					}else{
						isValid = (item[key] == validJson[key]);
					}
				}
				return isValid;
			});
			jqGrid.loadLocal(searchData);
		});

		$supplistModal.on('click','.js-confirm', function () {
			var rows = $('#jqGridsup').jqGrid("getGridParam", "selarrrow");
			var renderHTML = [];
			$.each(rows,function(i,r){
				if(supplierList[r]) return true;
				var rowData = $('#jqGridsup').jqGrid('getRowData',r);//获取选中行的数据（单行）
                //数据加入缓存
                supplierList[r] = rowData;
			});
            var rowNum = 0;
            supplierListArray.splice(0, supplierListArray.length);//清空数组
            $.each(supplierList, function (i, d) {
                supplierListArray[rowNum] = d;
                rowNum++;
            });

            $("#supplierListJqGrid").jqGrid("clearGridData");
            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListArray}).trigger('reloadGrid');
            $('#supplistModal').modal('hide');
            // $('#supplierListTable tbody').
            // append(renderHTML.join(''));
            // resetSeq();
            // $(window).scrollTop($(window).scrollTop() + 33.6 * rows.length);

		});

		//删除
		$('#gview_supplierListJqGrid').on('click','.order-del-btn',function(){
			var id = $(this).data("id");
			$(this).parent().parent("tr").remove();
			//从缓存里面删除
			delete supplierList[id];
            supplierListArray.splice(0, supplierListArray.length);//清空数组
			var rowNum = 0;
            $.each(supplierList, function (i, d) {
                supplierListArray[rowNum] = d;
                rowNum++;
            });
            $("#supplierListJqGrid").jqGrid("clearGridData");
            $("#supplierListJqGrid").jqGrid('setGridParam', {datatype: 'local', data: supplierListArray}).trigger('reloadGrid');
		});

		//重新设置序号
		function resetSeq(){
			var $tds = $('#supplierListTable tbody').find('tr td:first-child');
			$tds.each(function (i,el) {
				$(this).html(i+1);
			});
		}

	})();
	function deleteFormatter(cellvalue, options, rawObject) {
        //DOM操作
        var deleteTmp = '<a class="order-del-btn" data-id="'+ rawObject.supplierCode+'"><i class="red icon icon-trash"></i>&nbsp; 删除</a>';
        return deleteTmp;
    }
	//END


	//角色设置
	(function(){
		var jqGrid = null;
		var roleData = [];
		var $myModaphone = $('#myModaphone');
		var $form = $myModaphone.find('form');
		$myModaphone.on('shown.zui.modal',function(){
			getAttData("#jqGridphone","#jqGridPagerphone");
		});

        $myModaphone.on('hide.zui.modal', function () {
            $form[0].reset();
        });
		function getAttData(grid,page){
			jqGrid = RFQ.jqGrid(grid).init({
				datatype:"local",
				multiselect: true,
				colModel: [
					{
						label: '主键',
						name: 'userId',
						width: 20,
						key: true,
						hidden: true
					},
					{
						label: '工号',
						name: 'jobCode',
						width: 20,
					},
					{
						label: '姓名',
						name: 'userName',
						width: 20,
					},
					{
						label: '所属科室',
						name: 'userOffice',
						width: 20,
					},
					{
						label: '职位',
						name: 'userTitle',
						width: 20
					}
				],
				pager: page,
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
			$.post(ctx+ '/rfqProjectUserNew/rfqProjectUserListNew',{}, function (data) {
				roleData = (data.list||[]).filter(function (item) {
					return !projectUserList[item.userId];
				});

				jqGrid.loadLocal(roleData);
			},'json');
		}

		$("#roleSearch").click(function () {
			var validJson = {};
			$form.find(':text,select').each(function () {
				this.value && (validJson[this.name] = this.value);
			});
			var searchData = roleData.filter(function (item) {
				var isValid = true;
				for(var key in validJson){
					if(!isValid) return false;
					//if(key == 'userOffice' || key == 'userName'){
						isValid = item[key] && ~item[key].indexOf(validJson[key]);//模糊匹配
					//}else{
					//	isValid = (item[key] == validJson[key]);
					//}
				}
				return isValid;
			});
			jqGrid.loadLocal(searchData);
		});

		//DOM操作
		var rowIndex = 0;
		var rowTmp = '<tr id="puser_{userId}"> <td data-name="userId" data-value="{userId}">{index}</td> <td>{jobCode}</td> <td>{userName}</td> <td>{userOffice}</td> <td>{userTitle}</td> <td><input name="" type="checkbox"></td> <td><input name="" type="checkbox"></td> <td><input class="js-money" name="" type="checkbox"></td> <td><a class="order-del-btn" data-id="{userId}"><i class="icon icon-trash red"></i>&nbsp; 删除</a></td> </tr>';

		//if(module == 'edit'){
		//当前存在的数据加入缓存
		$('#roleTable tbody').find('tr').each(function () {
			var tmp = {};
			$(this).find('td').each(function () {
				var $this = $(this);
				var name = $this.data('name');
				if(!name) return true;
				tmp[name] = $this.data('value');
			});
			projectUserList[tmp.userId] = tmp;
			rowIndex ++;
		});
		//}
		RFQ.d(projectUserList);

		$('#myModaphone').on('click','.js-confirm', function () {
			var rows = $('#jqGridphone').jqGrid("getGridParam", "selarrrow");
			var renderHTML = [];
			$.each(rows,function(i,r){
				if(projectUserList[r]) return true;
				var rowData = $('#jqGridphone').jqGrid('getRowData',r);//获取选中行的数据（单行）
				rowData.index = rowIndex + 1;
				renderHTML.push(rowTmp.format(rowData));
				rowIndex ++;
				projectUserList[r] = rowData;
			});
			$roleTable.find('tbody').append(renderHTML.join(''));
			var money = +$assureMoney.filter(':checked').val();
			if(!money){
				$roleTable.find('.js-money').attr('disabled',true);
			}
			$('#myModaphone').modal('hide');
			resetSeq();
			RFQ.d(projectUserList);
		});

		//删除
		$('#roleTable').on('click','.order-del-btn',function(){
			var id = $(this).data("id");
			$(this).parent().parent("tr").remove();
			delete projectUserList[id];
			rowIndex >0 && rowIndex--;
			resetSeq();
			RFQ.d(projectUserList);
		});

		//重新设置序号
		function resetSeq(){
			var $tds = $('#roleTable tbody').find('tr td:first-child');
			$tds.each(function (i,el) {
				$(this).html(i+1);
			});
		}
	})();
	//END

	var editor,editor2,editor3,editorMemo;
	//商务与技术条款
	(function(){

		<!--富文本JS-->
		KindEditor.ready(function(K) {
			editor = K.create('textarea#contentSimple', {
				resizeType : 1,
				allowPreviewEmoticons : false,
				allowImageUpload : false,
				items : []
			});
		});
		KindEditor.ready(function(K) {
			editor2 = K.create('textarea#contentSimple2', {
				resizeType : 1,
				allowPreviewEmoticons : false,
				allowImageUpload : false,
				items : []
			});
		});
		KindEditor.ready(function(K) {
			editor3 = K.create('textarea#contentSimple3', {
				resizeType : 1,
				allowPreviewEmoticons : false,
				allowImageUpload : false,
				items : []
			});
		});

		KindEditor.ready(function(K) {
			editorMemo = K.create('textarea#memo', {
				resizeType : 1,
				allowPreviewEmoticons : false,
				allowImageUpload : false,
				items : []
			});
		});

		var jqGrid = null;
		var jqGrid2 = null;

		$('#myModaBL').on('shown.zui.modal',function(){
			/*if(!jqGrid){*/
				jqGrid = getAttData("BL","#jqGrid","#jqGridPager");
				jqGrid.reload();
			/*}*/
			jqGrid.resize();
			jqGrid.resetSelection();
		});
		$('#myModaTL').on('shown.zui.modal',function(){
			/*if(!jqGrid2){*/
				jqGrid2 = getAttData("TL","#jqGrid1","#jqGridPager1");
				jqGrid2.reload();
			/*}*/
			jqGrid2.resize();
			jqGrid.resetSelection();
		});
		function getAttData(type,grid,page){
			return RFQ.jqGrid(grid).init({
				url:ctx+ '/rfqLibTerms/rfqLibTermsList',
				multiselect: true,
				autoLoad:false,
				colModel: [
					{
						label: '序号',
						name: 'termId',
						index: 'TERM_ID',
						width: 40,
						key: true,
						hidden:true
					},
					{
						label: '条款名称',
						name: 'title',
						index: 'TITLE',
						width: 80
					},
					{
						label: '条款内容',
						name: 'content',
						index: 'CONTENT',
						width: 110
					},
					{
						label: '备注',
						name: 'remark',
						index: 'REMARK',
						width: 110
					}
				],
				postData:{type:type},
				prmNames: {
					id: 'termId'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
				},
				sortname: 'TERM_ID',
				sortorder: 'asc',
				pager:page,
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
		}

		$('#myModaBL').on('click','.js-confirm', function () {
			var rows = $('#jqGrid').jqGrid("getGridParam", "selarrrow");
			var renderHTML = [];
			$.each(rows,function(i,r){
				var rowData = $('#jqGrid').jqGrid('getRowData',r);//获取选中行的数据（单行）
				renderHTML.push("条款名："+rowData.title+"；条款内容："+rowData.content);
			});
			editor3.html(editor3.html() + renderHTML.join('<br/>'));
			$('#myModaBL').modal('hide');
		});

		$('#myModaTL').on('click','.js-confirm', function () {
			var rows = $('#jqGrid1').jqGrid("getGridParam", "selarrrow");
			var renderHTML = [];
			$.each(rows,function(i,r){
				var rowData = $('#jqGrid1').jqGrid('getRowData',r);//获取选中行的数据（单行）
                renderHTML.push("条款名："+rowData.title+"；条款内容："+rowData.content);
			});
			editor2.html(editor2.html() + renderHTML.join('<br/>'));
			$('#myModaTL').modal('hide');
		});
	})();
	//END


	//附件上传
	//BEGIN
	(function () {
		var $myModa2 = $('#myModa2');
		var $attachmentList1 = $('#attachmentList1');
		var $attachmentList2 = $('#attachmentList2');
		var rowTmp = '<tr data-clone="orginal"> <td data-order="true">1</td> <td>{originalFilename}</td> <td>{fileSize}KB</td> <td class="wordWrap">{fileDeclaration}</td> <td style="padding:6px"><a href="javascript:;" data-key="{downloadFilename}_{type}" class="text-danger order-del-btn"><i class="icon-trash"></i> 删除</a><a href="{fileDown}"><i class="icon icon-download-alt green "></i>&nbsp;下载</a></td> </tr>';

		//var uploadComponent = new UploadComponent({
		//	divId: 'container_doc',
		//	code: 'AAAA',
		//	documentId: '1111',
		//	containerId:'container_doc_upload_form',
		//	fileType: 'txt,doc,docx,xls,xlsx,pdf,png,jpg,jpeg,gif,bmp',
		//	inputDiv: 'fileup',
		//	styleType:"normal",
		//	uploadUrl:ctx + "/common/uploadFile",
		//	success: function (data) {
		//		if(data.status == 'success'){
		//			var result = JSON.parse(data.attachmentsVo);
		//			$("#fileName").val(result.originalFilename);
		//			RFQ.d(result);
		//			$myModa2.data('_result', result);
		//			$myModa2.find('.js-confirm').attr('disabled',false);
		//		}else{
		//			$.zui.messager.show(data.message, {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
		//		}
		//	}
		//});
        //
		$('button.attachmentBtn').on('click', function () {
			$myModa2.data('_type',$(this).data('type'));
		});

		//附件
		var types=[".jpg",".jpeg",".gif",".png",".doc",".docx",".xls",".xlsx",".pdf"];
		var maxSize=104857600;//100M，单位:B

        if(navigator.appName == "Microsoft Internet Explorer"){
                $("#myModa2").on('show.zui.modal', function () {
                    //初始化flash插件
                    initPlupload2(maxSize,types);
                    //关闭时清理页面
                    initEvent();
                });
        }else {
            //初始化flash插件
            initPlupload(maxSize,types);
            //关闭时清理页面
            initEvent();
        }
        //当前存在的数据加入缓存
        $('#attachmentList1 tr,#attachmentList2 tr').each(function () {
            var tmp = {};
            $(this).find('[data-name]').each(function () {
                var $this = $(this);
                var name = $this.data('name');
                if(!name) return true;
                tmp[name] = $this.data('value');
            });
            attachmentList[tmp.downloadFilename + '_'+tmp.type] = tmp;
        });

		$myModa2.on('click','.js-confirm', function () {
			var type = $myModa2.data('_type');
			var data = $myModa2.data('_result');
			//var fileEl = $myModa2.find(':file')[0];
			//if(!fileEl.value){
			//	RFQ.warn('未选择上传文件');
			//	return false;
			//}
			//if(!data.fileSize){
			//	RFQ.warn('文件未上传完成，请重新上传');
			//	return false;
			//}
			if(data==undefined || data==''){
				RFQ.error("您还没选择文件！");
			}
			if(!data.fileSize){
				RFQ.warn('文件未上传完成，请重新上传');
				return false;
			}
			data.type = type;
            data.fileDeclaration = $myModa2.find('textarea').val();
			data.fileDown = ctx+"/rfqAttachments/fileDownload?file="+data.downloadFilename+"&oriName="+data.originalFilename;
			var $container = (type == 'R' ? $attachmentList2:$attachmentList1);
			attachmentList[data.downloadFilename + '_'+data.type] = data;
			$container.append(rowTmp.format(data));
			$myModa2.modal('hide');
			resetSeq($container);
		});

		//删除
        $attachmentList1.on('click','.order-del-btn',deleteHandle);
        $attachmentList2.on('click','.order-del-btn',deleteHandle);

        function deleteHandle(){
            var $this = $(this);
            var key = $(this).data("key");
            $this.parent().parent("tr").remove();
            delete attachmentList[key];
            resetSeq($this.closest('tbody'));
            RFQ.d(attachmentList);
        }

		//重新设置序号
		function resetSeq($tbody){
			var $tds = $tbody.find('tr td:first-child');
			$tds.each(function (i,el) {
				$(this).html(i+1);
			});
		}
	})();
	//END

	//常用地址设置
	(function(){
		var jqGrid = null;
		/*$('#prouser').click(function(){
			getAttData("#jqGridphone","#jqGridPagerphone");

		});*/
		$('#myModa8').on('shown.zui.modal', function() {
			if(!jqGrid){
				jqGrid = initAddreJqGrid();
				jqGrid.reload();
			}
			jqGrid.resetSelection();
			jqGrid.resize();
		});

		function initAddreJqGrid(grid,page){
			return RFQ.jqGrid('#AddreJqGrid').init({
				url:ctx+ '/rfqCommonAddress/rfqCommonAddressList',
				autoLoad:false,
				singleSelect: true,
				maxHeight:400,
				colModel: [
					{
						label: '主键',
						name: 'id',
						index: 'ID',
						key: true,
						hidden: true
					},
					{
						label: '省id',
						name: 'deliveryProvinceCode',
						index: 'DELIVERY_PROVINCE_CODE',
						hidden: true
					},
					{
						label: '省',
						name: 'deliveryProvince',
						index: 'DELIVERY_PROVINCE',
					},
					{
						label: '市id',
						name: 'deliveryCityCode',
						index: 'DELIVERY_CITY_CODE',
						hidden: true
					},
					{
						label: '市',
						name: 'deliveryCity',
						index: 'DELIVERY_CITY',
					},
					{
						label: '区id',
						name: 'deliveryAreaCode',
						index: 'DELIVERY_AREA_CODE',
						hidden: true
					},
					{
						label: '区',
						name: 'deliveryArea',
						index: 'DELIVERY_AREA',
					},
					{
						label: '具体地址',
						name: 'deliveryAddress',
						index: 'DELIVERY_ADDRESS',
					},
					{
						width: 80,
						label: '操作',
						name: '',
						index: '',
						sortable:false,
						formatter: optFormatter
					}
				],
				sortname: 'ID',
				sortorder: 'desc',
				pager: '#AddreJqGridPager',
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
		}

		function optFormatter(cellvalue, options, rawObject) {
			var detailBtn = '<span class="ml5"><a  href="javascript:delCommonAddress(\'' + rawObject.id + '\')"><i class="icon icon-trash red"></i> 删除</a></span>';
			return detailBtn;
		};


		window.delCommonAddress =  function(id){
			var data = {
				id : id
			};
			RFQ.post(ctx+'/rfqCommonAddress/delRfqCommonAddress',data,function(data){
				RFQ.jqGrid('#AddreJqGrid').reload();
			});
		};

		window.addAddress = function(){
			var ids = $('#AddreJqGrid').jqGrid('getGridParam', 'selarrrow');
			//console.log('ids:'+ids);
			if(ids != undefined && ids.length==0){
				$('#myModa8').modal('hide');
				return;
			}else {
				var rowData = $('#AddreJqGrid').jqGrid('getRowData',ids);//获取选中行的数据（单行）
				//赋值
				selProvince("1",rowData);
                $("#deliveryAddress").val(rowData.deliveryAddress);
				$('#myModa8').modal('hide');
			}
		}
	})();
	//END


	//采购组织维护常用地址
	(function(){
		$('#modalAddress').on('shown.zui.modal', function() {
			$("#deliveryProvince2").val("");
			$("#deliveryCity2").val("");
			$("#deliveryArea2").val("");
			$("#deliveryAddress2").val("");
			//显示省市区
			showProvince('level','1','2');
			//选择省市chang事件
			$('#deliveryProvince2').bind('change', function(){selProvince('2')} );
			$('#deliveryCity2').bind('change', function(){selCity('2')});
		});

		window.ajaxToAddData = function(){
			var data = {
				deliveryProvince : $("#deliveryProvince2").val(),
				deliveryCity : $("#deliveryCity2").val(),
				deliveryArea : $("#deliveryArea2").val(),
			    deliveryAddress : $("#deliveryAddress2").val()
			};
			RFQ.post(ctx+'/rfqCommonAddress/saveRfqCommonAddress',data,function(data){
				$('#modalAddress').modal('hide');
				var jqGrid = RFQ.jqGrid('#AddreJqGrid');
				jqGrid.reload();
				//$('#myModa8').modal('ajustPosition', 'center')
			});
		}
	})();
	//END

	//表单提交
	(function(){
		var $requestId = $('#requestId');
		var $requestRfqNum = $('#requestRfqNum');
		var $myModa9 = $('#myModa9');
		var $myModa6 = $('#myModa6');
		//表单操作按钮
		$('#dataform').on('click','.js-form-btn',function(){
			var $this = $(this);
			var type = $this.data('type');
			if(type==1 || type== 3 || type==4){ //1 保存  4 发布 3 预览 统一提交表单
				var extras = fecthExtraParams();
				var url = '';
				if(type == 1){
					url = (module=='edit'?'saveRfqRequestNocheck/edit': 'saveRfqRequestNocheck/add');
				}else if(type == 3){
					url = 'rfqRequestPreview';
				}else if(type == 4){
					url = (module=='edit'?'updateRfqRequestData': 'saveRfqRequest/add');
					if(!validate2000(editor)){
						RFQ.error("报名要求最多输入2000字符！");
						return;
					}
					if(!validate2000(editor3)){
						RFQ.error("商务条款最多输入2000字符！");
						return;
					}
					if(!validate2000(editor2)){
						RFQ.error("技术条款最多输入2000字符！");
						return;
					}
					if(!validate2000(editorMemo)){
						RFQ.error("询单备注最多输入2000字符！");
						return;
					}
				}
				//提交前保存物料临时数据
				var $requestItemTable = $('#datatable-requestItemTable');
				var rfqDTable = $requestItemTable.data('_rfqDTable');
				if(rfqDTable.options.beforePagination.call(rfqDTable)){ //临时数据保存成功
					rfqDTable.load();
					RFQ.form('#dataform').ajaxSubmit(ctx+ '/rfqRequest/'+url,extras, function (data) {
						//这里防止二次提交保存两条数据
						if(module!='edit' && (type == 1 || type == 4 )){
							var obj = data.obj;
							if(!obj.requestId) return;
							$requestId.val(obj.requestId);
							$requestRfqNum.val(obj.requestNo);
							module = 'edit';
							id = obj.requestId;
						}
						if(type == 1){ //保存成功
							//RFQ.renderText('#myModa9',data.obj);
							//$myModa9.modal('show');
							var messageList1 = data.obj.messageList1;
							//console.log('messageList1'+messageList1);
							if(messageList1 !=null && messageList1 != ""){
								RFQ.warn('保存成功!['+messageList1+"]");
							}else{
								RFQ.info('保存成功!');
							}
							window.location.href =ctx+'/rfqRequest/toUpdateRfqRequest?id='+ data.obj.requestId;
						}
						if(type == 4){ //保存成功并发布
							var messageList1 = data.obj.messageList1;
							//console.log('messageList1'+messageList1);
							if(messageList1!="" && messageList1!=null){
									RFQ.warn(messageList1)
							}
							RFQ.renderText('#myModa6',data.obj);
							$myModa6.data('id',data.obj.requestId);
							$myModa6.modal('show');
							//输出审批流
							$("#appro").empty();
							var appList = data.obj.appList;
							//console.log('appList'+appList);
							if(appList!="" && appList!=null){
								$("#appro").append("<option value='0'>无需审批</option>");
								$.each(appList||[], function(i,val){
									var type = "";
									if(val.type == "1"){
										type = "标准";
									}else if(val.type == "2"){
										type = "灵活";
									}else{
										type = "未知";
									}
									$("#appro").append("<option value=" + val.number+ ',' + val.type + ">" + type +":"+val.wfDefineName +  "</option>");
								});
							}else{
								$("#appro").attr("disabled",true);
								$("#appro").append("<option value='0'>无有效审批</option>");
							}
						}
						if(type == 3){
							var messageList1 = data.obj.messageList1;
							//console.log('messageList1'+messageList1);
							if(messageList1!="" && messageList1!=null){
								RFQ.warn(messageList1);
							}
							RFQ.openLinkInBlank(ctx+'/rfqRequest/toRfqRequestPreview');
							//window.open(ctx+'/rfqRequest/toRfqRequestPreview');
							//location.href=ctx+'/rfqRequest/toRfqRequestPreview';
						}
					});
				}
			}else if(typeof(type)!="undefined"){ //删除
				//RFQ.info('删除！');
				RFQ.confirm('确认要删除吗？', function () {
					RFQ.post(ctx+'/rfqRequest/deleteIsDeteled',{id:id}, function () {
						RFQ.info('操作成功');
						location.href=ctx+'/rfqRequest/init';
					});
				});
			}
		});

		//发布摸态框按钮事件绑定
		$myModa6.on('click','.modal-footer a',function(){
			var type = $(this).data('type');
			var selAudit = $('#appro').val();
			if(type == 1){ //确认提交
				var procDefType;
				if(selAudit != 0){   //选择审批
					procDefType = selAudit.split(",")[1];
					if(procDefType == 2){   //灵活流程
						$('#myModa6').modal('hide');
						$('#myRole').modal('show');
						return;
					}else{
						var $confirmBtn = $myModa6.find('.modal-footer .btn-primary');
						$confirmBtn.attr('disabled',true);
						postforData([]);
					}
				}else {
					var $confirmBtn = $myModa6.find('.modal-footer .btn-primary');
					$confirmBtn.attr('disabled',true);
					postforData([]);
				}
			}else if(type == 2){ //返回修改
				location.href=ctx+'/rfqRequest/toUpdateRfqRequest?id='+id;
			}
		});

		//抓取额外参数
		function fecthExtraParams(){
			//组装额外参数 选取的供应商以及角色
			var extras = {};
			if(!$.isEmptyObject(supplierList)){
				var index = 0,tmp;
				for(var key in supplierList){
					tmp = supplierList[key];
					extras['supplierList['+index+'].seq'] = index+1;
					extras['supplierList['+index+'].companyId'] = tmp.supplierCode;
					extras['supplierList['+index+'].supplierCode'] = tmp.supplierCode;
					extras['supplierList['+index+'].supplierName'] = tmp.supplierName;
					extras['supplierList['+index+'].linkmanName'] = tmp.linkmanName;
					extras['supplierList['+index+'].answerUsername'] = tmp.linkmanName;//适配报名表联系人
					extras['supplierList['+index+'].linkmanTelphone'] = tmp.linkmanTelphone;
					extras['supplierList['+index+'].isBindWechat'] = tmp.isBindWechat;
					index++;
				}
			}
			if(!$.isEmptyObject(projectUserList)){
				var index = 0,tmp;
				$('#roleTable tbody').find('td[data-name="userId"]').each(function () {
					var key = $(this).data('value');
					//for(var key in projectUserList){
						tmp = projectUserList[key];
						extras['projectUserList['+index+'].seq'] = index+1;
						extras['projectUserList['+index+'].userId'] = tmp.userId;
						extras['projectUserList['+index+'].userOffice'] = tmp.userOffice;
						extras['projectUserList['+index+'].jobCode'] = tmp.jobCode;
						extras['projectUserList['+index+'].userName'] = tmp.userName;
						extras['projectUserList['+index+'].userTitle'] = tmp.userTitle;
						//获取选中的权限
						var $checks = $('#puser_' + key).find(':checkbox');
						extras['projectUserList['+index+'].viewQx'] = $checks.eq(0).prop('checked')?1:0;
						extras['projectUserList['+index+'].optionQx'] = $checks.eq(1).prop('checked')?1:0;
						extras['projectUserList['+index+'].caiwuQx'] =  $checks.eq(2).prop('checked')?1:0;
						index++;
					//}
				});
			}

			//checkbox处理
			$(':checkbox').each(function () {
				var $this = $(this);
				var name = $this.data('name');
				if(!name) return true;
				extras[name] = $this.prop('checked')?1:0;
			});


			//富文本e
			extras['requestBo.requestBusiTerms'] = editor3.html();
			extras['requestBo.requestTecTerms'] = editor2.html();
			extras['preauditBo.requirementDesc'] = editor.html();
			extras['requestBo.memo'] = editorMemo.html();//询单备注

			//组装物料行信息
			//$('#requestItemData').find('.datatable:visible input').each(function(){
			//	extras[$(this).data('name')] = this.value;
			//});
			//var $requestItemTable = $('#datatable-requestItemTable');
			//var rfqDTable = $requestItemTable.data('_rfqDTable');

			//$requestItemTable.find('.flexarea tbody tr').each(function(i){
			//	totalCount = i;
			//	$(this).find('input[data-name]').each(function (i2) {
			//		extras['requestItemList['+i+'].'+$(this).data('name')] = this.value;
			//	});
			//});

            //组装附件信息
            if(!$.isEmptyObject(attachmentList)){
                var index = 0,tmp;
                for(var key in attachmentList){
                    tmp = attachmentList[key];
                    extras['attachmentsList['+index+'].seq'] = index+1;
                    extras['attachmentsList['+index+'].type'] = tmp.type;
                    extras['attachmentsList['+index+'].downloadFilename'] = tmp.downloadFilename;
                    extras['attachmentsList['+index+'].fileSize'] = tmp.fileSize;
                    extras['attachmentsList['+index+'].originalFileType'] = tmp.originalFileType;
                    extras['attachmentsList['+index+'].originalFilename'] = tmp.originalFilename;
                    extras['attachmentsList['+index+'].downloadUrl'] = tmp.downloadUrl;
                    extras['attachmentsList['+index+'].fileDeclaration'] = tmp.fileDeclaration;
                    index++;
                }
            }
			return extras;
		}

        $("#supplierListJqGrid").jqGrid('resizeGrid');
	})();
	//END

	$('input[name="requestBo.title"]').keyup(function () {
        $('#_title').html($(this).val());
    });
    $('input[name="requestBo.planNo"]').keyup(function () {
        $('#_planNo').html($(this).val());
    });
});

//ajax提交方法
function postforData(rowDataLists){
	var id = $('#myModa6').data('id');
	var publicBiddingFlag = $('input[name="rulesBo.publicBiddingFlag"]').prop('checked')?1:0;
	RFQ.post(ctx + '/rfqRequest/saveRfqRequest/publish', {
		id: id,
		selAudit: $('#appro').val(),
		publicBiddingFlag: publicBiddingFlag,
		rowDataLists: JSON.stringify(rowDataLists)
	}, function (data) {
		location.href = ctx + '/rfqRequest/init';
	});
}

/**
 * 显示初始省市区信息
 */
function showProvince(key1,value1,flag,rowData) {
    //flag：''询单常用地址 '2' 采购组织常用地址维护
    //console.log('key1:'+key1)
    //key值获取变量的方法
    var data = {},key=key1;
    data[key]=value1;
    var province = "#deliveryProvince";
    if(flag=='2') province = "#deliveryProvince2";
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: data,
        cache: false,
        success: function (data) {
            if (null != data && "" != data) {
                $(province).empty();
                $.each(data, function (i, val) {
                    $(province).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                /*for (var i = 0; i < data.length; i++) {
                 $("#deliveryProvince").append("<option value=" + data[i].code + ">" + data[i].name + "</option>");
                 }*/
                selProvince(flag,rowData);
            } else {
                $.zui.messager.show('sorry,区域信息刷新出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            }
        }
    });
}

/**
 * 选择省
 */
function selProvince(flag,rowData){ //rowData需要回显得数据
    var province = "#deliveryProvince";
    var city = "#deliveryCity";
    var area = "#deliveryArea";
    if(flag=='2'){
        var province = "#deliveryProvince2";
        var city = "#deliveryCity2";
        var area = "#deliveryArea2";
    }
    if(rowData!=null){
        $(province).val(rowData.deliveryProvinceCode+','+rowData.deliveryProvince);
    }
    var code = $(province).val().substring(0,6);
    //console.log('province:'+code)
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: {
            pCode: code
        },
        cache:false,
        success: function (data) {
            if (null!=data && ""!=data) {
                //清空市区select
                $(city).empty();
                $(area).empty();
                $.each(data, function(i,val){
                    $(city).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                if(rowData!=null){
                    $(city).val(rowData.deliveryCityCode+','+rowData.deliveryCity);
                }
                selCity(flag,rowData);
            } else {
                $.zui.messager.show('sorry,出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            };
        }
    });
}

/**
 * 选择市
 */
function selCity(flag,rowData){//rowData需要回显得数据
    var city = "#deliveryCity";
    var area = "#deliveryArea";
    if(flag=='2'){
        var city = "#deliveryCity2";
        var area = "#deliveryArea2";
    }
    var code = $(city).val().substring(0,6);
    //console.log('city:'+code)
    $.ajax({
        type: "POST",
        url: ctx+"/rfqRequest/refreshArea",
        data: {
            pCode: code
        },
        cache:false,
        success: function (data) {
            if (null!=data && ""!=data) {
                //清空区select
                $(area).empty();
                $.each(data, function(i,val){
                    $(area).append("<option value=" + val.code+','+val.name + ">" + val.name + "</option>");
                });
                if(rowData!=null){
                    $(area).val(rowData.deliveryAreaCode+','+rowData.deliveryArea);
                }
            } else {
				//清空区select
				$(area).empty();
                //$.zui.messager.show('sorry,出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
            }
        }
    });
}
